package com.hotelManager.www.service;

import com.hotelManager.www.dao.SignInDao;
import com.hotelManager.www.po.SignInRecord;
import com.hotelManager.www.util.JDBCUtils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 签到服务类
 * 实现签到相关功能
 */
public class SignInService {
    private final SignInDao signInDao;

    public SignInService() {
        this.signInDao = new SignInDao();
    }

    /**
     * 检查用户今日是否已签到
     * @param userId 用户ID
     * @return 是否已签到
     */
    public boolean isSignedInToday(int userId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            LocalDate today = LocalDate.now();
            Date sqlDate = Date.valueOf(today);
            return signInDao.isSignedInToday(conn, userId, sqlDate);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    /**
     * 获取用户连续签到天数
     * @param userId 用户ID
     * @return 连续签到天数
     */
    public int getConsecutiveSignInDays(int userId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return signInDao.getConsecutiveSignInDays(conn, userId);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    /**
     * 记录签到
     * @param userId 用户ID
     * @param points 获得的积分
     * @return 记录是否成功
     */
    public boolean recordSignIn(int userId, int points) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);

            // 打印接收到的用户ID和积分
            System.out.println("记录签到 - 接收到的用户ID: " + userId + ", 积分: " + points);

            // 创建签到记录
            SignInRecord record = new SignInRecord();
            record.setUserId(userId);
            record.setSignInDate(Date.valueOf(LocalDate.now()));
            record.setPointsEarned(points);

            // 打印创建的签到记录
            System.out.println("记录签到 - 创建的签到记录: " + record);

            boolean success = signInDao.insert(conn, record);
            if (success) {
                conn.commit();
                System.out.println("记录签到 - 签到记录插入成功，事务已提交");
            } else {
                conn.rollback();
                System.out.println("记录签到 - 签到记录插入失败，事务已回滚");
            }
            return success;
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                    System.out.println("记录签到 - 发生异常，事务已回滚");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
            System.out.println("记录签到 - 数据库连接已关闭");
        }
    }


    /**
     * 获取用户签到记录
     * @param userId 用户ID
     * @return 签到记录列表
     */
    public List<SignInRecord> getSignInRecords(int userId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return signInDao.getSignInRecordsByUserId(conn, userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }
    
    /**
     * 获取所有用户的签到统计信息
     * @return 签到统计信息
     */
    public Map<String, Object> getAllUsersSignInStatistics() {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            
            // 获取总签到次数
            int totalSignIns = signInDao.getTotalSignIns(conn);
            
            // 获取今日签到人数
            int todaySignIns = signInDao.getTodaySignIns(conn);
            
            // 获取连续签到7天以上的用户数量
            int consecutiveSignIns = signInDao.getConsecutiveSignInsCount(conn, 7);
            
            // 获取签到最多的前10名用户
            List<Map<String, Object>> topSignInUsers = signInDao.getTopSignInUsers(conn, 10);
            
            // 获取最近7天的签到趋势
            List<Map<String, Object>> signInTrend = signInDao.getSignInTrend(conn, 7);
            
            // 组装统计结果
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalSignIns", totalSignIns);
            statistics.put("todaySignIns", todaySignIns);
            statistics.put("consecutiveSignIns", consecutiveSignIns);
            statistics.put("topSignInUsers", topSignInUsers);
            statistics.put("signInTrend", signInTrend);
            
            return statistics;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    /**
     * 获取签到趋势数据
     * @param days 天数
     * @return 签到趋势数据
     */
    public List<Map<String, Object>> getSignInTrend(int days) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return signInDao.getSignInTrend(conn, days);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    /**
     * 获取签到排行榜
     * @param limit 限制数量
     * @return 签到排行榜数据
     */
    public List<Map<String, Object>> getTopSignInUsers(int limit) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return signInDao.getTopSignInUsers(conn, limit);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    /**
     * 禁止用户签到
     * @param userId 用户ID
     * @return 操作是否成功
     */
    public boolean banUserSignIn(int userId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);

            // 更新用户签到状态
            boolean success = signInDao.updateUserSignInStatus(conn, userId, "banned");
            if (success) {
                conn.commit();
                return true;
            } else {
                conn.rollback();
                return false;
            }
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }

    /**
     * 解除用户签到限制
     * @param userId 用户ID
     * @return 操作是否成功
     */
    public boolean unbanUserSignIn(int userId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);

            // 更新用户签到状态
            boolean success = signInDao.updateUserSignInStatus(conn, userId, "active");
            if (success) {
                conn.commit();
                return true;
            } else {
                conn.rollback();
                return false;
            }
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            JDBCUtils.closeConnection(conn);
        }
    }
} 